/**
 * Phase 2 路由 - 多进程架构API
 * EndoSight-UC 医疗AI系统
 *
 * 提供多进程管理器的REST API路由
 * 包含进程状态、工作器监控、队列管理等端点
 */

import express from 'express';
import {
  getProcessStatus,
  getWorkersStatus,
  getQueueMonitor,
  submitEnhancedInference,
  getInferenceTaskStatus,
  cancelInferenceTask,
  getPerformanceMetrics,
  restartWorkers
} from '../controllers/phase2Controller.js';
import { authenticateToken } from '../middleware/auth.js';
import auditService from '../services/auditService.js';

const router = express.Router();

// 记录API访问的中间件
const logApiAccess = (req, res, next) => {
  const startTime = Date.now();

  res.on('finish', () => {
    const duration = Date.now() - startTime;

    auditService.logMedicalDataAccess({
      userId: req.user?.id || 'anonymous',
      sessionId: req.sessionId,
      patientId: null,
      dataType: 'api_access',
      accessType: req.method.toLowerCase(),
      accessReason: `Phase 2 API访问: ${req.path}`,
      dataBefore: null,
      dataAfter: {
        method: req.method,
        path: req.path,
        statusCode: res.statusCode,
        duration,
        timestamp: new Date().toISOString()
      }
    }).catch(error => {
      console.error('API访问日志记录失败:', error);
    });
  });

  next();
};

// 应用日志记录中间件到所有路由
router.use(logApiAccess);

// 进程管理器状态 API
router.get('/process/status', authenticateToken, getProcessStatus);

// 工作器状态监控 API
router.get('/workers/status', authenticateToken, getWorkersStatus);

// 队列监控 API
router.get('/queues/monitor', authenticateToken, getQueueMonitor);

// 增强AI推理 API
router.post('/scoring/enhanced-inference', authenticateToken, submitEnhancedInference);

// 推理任务状态查询 API
router.get('/scoring/task/:taskId/status', authenticateToken, getInferenceTaskStatus);

// 取消推理任务 API
router.delete('/scoring/task/:taskId', authenticateToken, cancelInferenceTask);

// 系统性能指标 API
router.get('/metrics/performance', authenticateToken, getPerformanceMetrics);

// 管理员功能 - 重启工作器
router.post('/admin/workers/restart', authenticateToken, restartWorkers);

// 健康检查端点（不需要认证）
router.get('/health', (req, res) => {
  try {
    // 检查进程管理器是否可用
    const systemStatus = processManager.getSystemStatus();
    const inferenceStatus = enhancedAIInferenceService.getServiceStatus();

    const health = {
      status: 'healthy',
      timestamp: new Date().toISOString(),
      version: '2.0.0',
      phase: 'Phase 2 - Multi-Process Architecture',
      components: {
        processManager: {
          status: systemStatus.isRunning ? 'healthy' : 'unhealthy',
          uptime: systemStatus.uptime,
          totalWorkers: systemStatus.totalWorkers
        },
        enhancedInferenceService: {
          status: inferenceStatus.isRunning ? 'healthy' : 'unhealthy',
          processingTasks: inferenceStatus.processingTasks,
          queueLength: inferenceStatus.metrics.queueLength
        },
        database: 'healthy',
        authentication: 'healthy'
      },
      metrics: {
        totalWorkers: systemStatus.totalWorkers,
        totalTasksProcessed: systemStatus.totalTasksProcessed,
        processingTasks: inferenceStatus.processingTasks,
        queueLength: inferenceStatus.metrics.queueLength
      }
    };

    // 如果关键组件不健康，返回503
    const criticalComponents = ['processManager', 'enhancedInferenceService'];
    const unhealthyComponents = criticalComponents.filter(
      comp => health.components[comp].status === 'unhealthy'
    );

    if (unhealthyComponents.length > 0) {
      health.status = 'unhealthy';
      health.issues = unhealthyComponents;
      return res.status(503).json(health);
    }

    res.json(health);

  } catch (error) {
    console.error('Phase 2健康检查失败:', error);
    res.status(503).json({
      status: 'unhealthy',
      timestamp: new Date().toISOString(),
      error: 'Health check failed',
      phase: 'Phase 2 - Multi-Process Architecture'
    });
  }
});

// 版本信息 API
router.get('/version', (req, res) => {
  res.json({
    success: true,
    data: {
      version: '2.0.0',
      phase: 'Phase 2 - Multi-Process Architecture',
      description: 'EndoSight-UC 医疗AI系统多进程架构',
      features: [
        'Multi-process AI inference',
        'Intelligent load balancing',
        'Priority task queuing',
        'Real-time monitoring',
        'Automatic failure recovery',
        'HIPAA compliant audit logging'
      ],
      apiEndpoints: [
        'GET /api/phase2/health - 健康检查',
        'GET /api/phase2/process/status - 进程管理器状态',
        'GET /api/phase2/workers/status - 工作器状态',
        'GET /api/phase2/queues/monitor - 队列监控',
        'POST /api/phase2/scoring/enhanced-inference - 增强AI推理',
        'GET /api/phase2/metrics/performance - 性能指标'
      ],
      timestamp: new Date().toISOString()
    }
  });
});

export default router;